<?php

require_once 'ActionFramework/start.php';

abstract class AbstractLoginAction extends Action {
	
	final public function trigger($request) {
		
		$user = $this->verify_credentials($request);
		// Check output type
		if (! ($user instanceof GeneralUser || $user === null)) {
			throw new Exception("verify_credentials shoudl return a user or null");
		}
		if ($user === null) {
			return $this->redirect_invalid_credentials();
		}
		if ($user instanceof User && $user->blocked) {
			// Only user has blocked attribute, that's why we have to check
			global $DISPATCHER;
			$DISPATCHER->dispatch_blocked();
		}
		$_SESSION['user'] = $user;
		global $DB;
		$DB->flag_login($user);
		return $this->redirect_valid_credentials($request);
		
	}
	
	/**
	 * Verify whether the request is really coming from the user
	 * @param Array $request
	 * @returns user, or null if not verified
	 */
	abstract public function verify_credentials(Array $request);
	
	/**
	 * Default redirect: message on home page 	
	 */
	public function redirect_invalid_credentials() {
		return r(new StartAction('The provided credentials are not correct.'))->trigger(array());
	}
	
	/**
	 * Default redirect: user or admin start page
	 */
	public function redirect_valid_credentials(Array $request) {
		$user = $_SESSION['user'];
		if ($user->admin) {
			return r(new AdminAction())->trigger($request);
		}
		else {
			return r(new ViewMatchingAction())->trigger($request);
		}
	}
	
}

?>
